package com.cfs.utils;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.xiaoleilu.hutool.exceptions.ExceptionUtil;

/**
 * Created by Administrator on 2017/9/28/028.
 */
public class ShiroUtils {

    private static Logger logger = LoggerFactory.getLogger(ShiroUtils.class);

    /**
     * 获取subject
     * @return
     */
    public static Subject getSubject(){
        return SecurityUtils.getSubject();
    }

    /**
     * 获取session
     * @return
     */
    public static Session getSession(){
        return getSubject().getSession(false);
    }

    /**
     * 登录
     * @param username
     * @param password
     * @param host
     * @param remberMe
     */
    public static void login(String username,String password,String host,boolean remberMe){
        try {
            UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken();
            usernamePasswordToken.setUsername(username);
            usernamePasswordToken.setPassword(password.toCharArray());
            usernamePasswordToken.setHost(host);
            usernamePasswordToken.setRememberMe(remberMe);
            getSubject().login(usernamePasswordToken);
        } catch (AuthenticationException e) {
            logger.error(ExceptionUtil.stacktraceToString(e));
        }
        logger.info("====={} 登录成功",username);
    }

    /**
     * 设置session
     * @param key
     * @param val
     */
    public static void setSession(String key,Object val){
        getSession().setAttribute(key, val);
    }

    /**
     * 退出
     */
    public static void logout(){
        getSubject().logout();
    }

    /**
     * 是否登录
     * @return
     */
    public static boolean isAuthenticated(){
        return getSubject().isAuthenticated();
    }

    /**
     * 角色检查
     * @param role
     * @return
     */
    public static boolean hasRole(String role){
        return getSubject().hasRole(role);
    }

    /**
     * 检查一组权限
     * @param roles
     * @return
     */
    public static boolean[] hasRole(List<String> roles){
         return getSubject().hasRoles(roles);
    }
}
